﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


//https://dotblogs.com.tw/berrynote/2016/08/18/200338


namespace Cshare_Json
{

    public class WeatherForecast
    {
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        public string Summary { get; set; }
    }

    public class Introduction
    {
        public string Name { get; set; }         //名稱
        public int Age { get; set; }             //年紀
        public bool Marry { get; set; }          //結婚
        public List<string> Habit { get; set; }  //興趣
    }


    public class haimingde
    { 
        public string OTP { get; set; }
        public JArray DataList { get; set; }
    }

    class Program
    {

        static void demo1()
        {
            WeatherForecast weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2019-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot"
            };
            string jsonString = JsonConvert.SerializeObject(weatherForecast);  //序列化
            Console.WriteLine("1.序列化:\r\n" + jsonString);

            WeatherForecast weatherForecast1 = JsonConvert.DeserializeObject<WeatherForecast>(jsonString); //json反序列化
            Console.WriteLine("\r\n1.反序列化:\r\nDate:{0},TemperatureCelsius:{1},Summary:{2}", weatherForecast1.Date, weatherForecast1.TemperatureCelsius, weatherForecast1.Summary);
        }


        static void demo2()
        {
            List<WeatherForecast> ListWeather = new List<WeatherForecast>()
            {
                new WeatherForecast(){Date=DateTime.Parse("2018-01-01"),TemperatureCelsius=10,Summary="cold"},
                new WeatherForecast(){Date=DateTime.Parse("2019-01-01"),TemperatureCelsius=15,Summary="cold"},
            };

            string jsonData = JsonConvert.SerializeObject(ListWeather);            //Newtonsoft.Json序列化
            Console.WriteLine("\r\n2.序列化" + jsonData);

            WeatherForecast[] descJsonWea = JsonConvert.DeserializeObject<WeatherForecast[]>(jsonData);//反序列化
            Console.WriteLine("\r\n2.反序列化:\r\nDate:{0},TemperatureCelsius:{1},Summary:{2}\r\nDate:{3},TemperatureCelsius:{4},Summary:{5}",
                descJsonWea[0].Date, descJsonWea[0].TemperatureCelsius, descJsonWea[0].Summary, descJsonWea[1].Date, descJsonWea[1].TemperatureCelsius, descJsonWea[1].Summary);

        }

        static void demo3()
        {
            string cjson = @"{ 'Date':'2020-01-01','TemperatureCelsius':'18','Summary':'warm'}";
            WeatherForecast descJsonStu = JsonConvert.DeserializeObject<WeatherForecast>(cjson);//反序列化
            Console.WriteLine("\r\n3.反序列化:\r\nDate:{0},TemperatureCelsius:{1},Summary:{2}", descJsonStu.Date, descJsonStu.TemperatureCelsius, descJsonStu.Summary);
        }

        static void demo4()
        {
            string json = "[{'name':'Jack','age':'25'},{'name':'KeKe','age':'20'}]";
            JArray jarr = JsonConvert.DeserializeObject<JArray>(json);
            Console.WriteLine("\r\n4.反序列化:\r\nname:{0},age:{1}\r\nname:{2},age:{3}", jarr[0]["name"].ToString(), jarr[0]["age"].ToString(),
                jarr[1]["name"].ToString(), jarr[1]["age"].ToString());



            string Json6 = "{ 'OTP':'START','DataList':[{ 'id':12,'mac':'12345678901'},{ 'id':11,'mac':'12345678901'}]}";
            haimingde dataSet3 = JsonConvert.DeserializeObject<haimingde>(Json6);
            Console.WriteLine(dataSet3.OTP);
            Console.WriteLine(dataSet3.DataList[0]["mac"] + "\r\n" + dataSet3.DataList[1]["id"]);



            string Json5 = "{\"OTP\":\"START\",\"DataList\":[{\"12\":{\"MAC\":\"FC12FD88B22321\"},\"11\":{\"MAC\":\"FC12FD88B22320\"},\"10\":{\"MAC\":\"FC12FD88B22319\"},\"09\":{\"MAC\":\"FC12FD88B22318\"},\"08\":{\"MAC\":\"FC12FD88B22317\"},\"07\":{\"MAC\":\"FC12FD88B22316\"},\"06\":{\"MAC\":\"FC12FD88B22315\"},\"05\":{\"MAC\":\"FC12FD88B22314\"},\"04\":{\"MAC\":\"FC12FD88B22313\"},\"03\":{\"MAC\":\"FC12FD88B22312\"},\"02\":{\"MAC\":\"FC12FD88B22311\"},\"01\":{\"MAC\":\"FC12FD88B22310\"}}]}";
            haimingde dataSet2 = JsonConvert.DeserializeObject<haimingde>(Json5);
            Console.WriteLine(dataSet2.OTP);
            Console.WriteLine(dataSet2.DataList[0]["12"]["MAC"] + "\r\n" + dataSet2.DataList[0]["11"]["MAC"]);
        }

        static void demo5()
        {
            Introduction Introduction = new Introduction
            {
                Name = "Berry",
                Age = 18,
                Marry = false,
                Habit = new List<string>
                {
                    "Sing",
                    "Dance",
                    "Code",
                    "Sleep"
                }
            };
            //轉成JSON格式
            string json1 = JsonConvert.SerializeObject(Introduction);
            //顯示
            Console.WriteLine("\r\n5.序列化:\r\n" + json1);



            string Json3 = "{ 'Name': 'Berry', 'Age': 18, 'Marry': false, 'Habit': [ 'Sing','Dance','Code','Sleep' ] }";
            Introduction Introduction1 = JsonConvert.DeserializeObject<Introduction>(Json3);

            Console.Write("\r\n5.反序列化:\r\nname:{0}\r\nage:{1}\r\nmarry:{2}\r\nHabit:", Introduction1.Name, Introduction1.Age, Introduction1.Marry);
            for (int i = 0; i < Introduction1.Habit.Count; i++)
            {
                Console.Write(Introduction1.Habit[i] + " ");
            }
            Console.Write("\r\n");
        }


        static void demo6()
        {

            //序列化成DataSet
            DataSet dataSet1 = new DataSet("dataSet"); //建立DataSet
            DataTable table = new DataTable("table"); //建立DataTable
            DataColumn idColumn = new DataColumn("id", typeof(int)); //建立id欄
            DataColumn itemColumn = new DataColumn("item"); //建立item欄

            //DataTable加入欄位
            table.Columns.Add(idColumn);
            table.Columns.Add(itemColumn);

            //DataSet加入Table
            dataSet1.Tables.Add(table);

            //跑回圈產生資料
            for (int i = 1; i < 5; i++)
            {
                DataRow newRow = table.NewRow();
                newRow["id"] = i;
                newRow["item"] = "這是第" + i + "個項目";
                table.Rows.Add(newRow);
            }

            //轉成JSON格式
            string json2 = JsonConvert.SerializeObject(dataSet1);

            //顯示
            Console.WriteLine("\r\n6.序列化:\r\n" + json2);

            //反序列化成DataSet
            //JSON字串
            string Json = "{ 'Table1': [ { 'id': 1, 'item': '這是第1個項目' }, { 'id': 2, 'item': '這是第2個項目' }, { 'id': 3, 'item': '這是第3個項目' }, { 'id': 4, 'item': '這是第4個項目' } ] }";

            //將JSON字串轉為DataSet
            DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(Json);

            //建立DataTable，並塞進dataSet的值
            DataTable dataTable = dataSet.Tables["Table1"];

            //顯示DataTable的筆數
            Console.WriteLine("\r\n6.反序列化:");

            //顯示DataTable的筆數
            foreach (DataRow row in dataTable.Rows)
            {
                Console.Write(row["id"] + " - " + row["item"]);
            }
            Console.Write("\r\n");
        }

        static void Main(string[] args)
        {
            demo1();
            demo2();
            demo3();
            demo4();
            demo5();
            demo6();
            Console.ReadLine();
        }
    }
}
